/**
 * 
 */
package any.gwt.client.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.google.gwt.http.client.URL;

/**
 * Query Builder.
 * 
 * @author keke <keke@codehaus.org>
 * @version 0.0.1
 * @revision $Revision:$
 */
public class QueryBuilder {
    private Map params;

    public QueryBuilder add(final String name, final String value) {
        if (params == null) {
            params = new HashMap();
        }
        params.put(name, value);
        return this;
    }

    public String build() {
        if (params == null) {
            return null;
        }
        final StringBuffer sb = new StringBuffer();
        final Iterator keyIter = params.keySet().iterator();
        boolean first = true;
        while (keyIter.hasNext()) {
            if (!first) {
                sb.append("&");
            }
            final String key = (String) keyIter.next();
            sb.append(URL.encodeComponent(key)).append("=").append(
                    URL.encodeComponent((String) params.get(key)));
            first = false;
        }
        return sb.toString();
    }
}
